package com.yunhaikeji.api.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ObjectUtils;

/**
 *  关于LiveGBS的所有接口 都应改放在这里
 *  https://gbs.liveqing.com:10010/apidoc/
 */
public class LiveGBSAPI {

    /**
     * 通道快照
     * @param url  LiveGBS服务器地址
     * @param serial  设备号
     * @return 返回设备快照
     */
    public static byte[] channelSnap(String url, String serial){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url + "/api/v1/device/channelsnap?realtime=true&serial=" + serial);
            //BUG wait for snap timeout[15s]
            //setConnectTimeout ：设置连接超时时间，单位毫秒。
            //setConnectionRequestTimeout ：设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
            //setSocketTimeout ：请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(15000).build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("Socket Timeout Exception, I will be back。");
        } finally {
            WebUtils.releaseTheBaby(httpClient, response);
        }
        return null;
    }

    /**
     * 查询设备通道列表  设备状态用这个
     * @param url LiveGBS服务器地址
     * @param serial 设备号
     * @return 通道列表  需要解析成EqChannelResult
     */
    public static String channelList(String url, String serial){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url + "/api/v1/device/channellist?online=true&serial=" + serial);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(15000).build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (!ObjectUtils.isEmpty(entity)) {
                    return EntityUtils.toString(entity);
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("Socket Timeout Exception, I will be back。");
        } finally {
            WebUtils.releaseTheBaby(httpClient, response);
        }
        return null;
    }

    /**
     * 查询设备通道树
     * @param url LiveGBS服务器地址
     * @return 查询设备通道树
     */
    public static String channelTree(String url){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url + "/api/v1/device/channeltree");
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(15000).build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if(!ObjectUtils.isEmpty(entity)) {
                   return EntityUtils.toString(entity);
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("各种网络错误， ConnectionTimeoutException，SocketTimeoutException，***无视吧。");
        } finally {
            WebUtils.releaseTheBaby(httpClient, response);
        }
        return null;
    }

    /**
     * 按日查询通道录像
     * @param url LiveGBS服务器地址
     * @param serial 设备编号
     * @param period 日期字符串 yyyyMMdd
     * @return 按日查询通道录像
     */
    public static String cloudRecord(String url, String code, String schemaCode, String period){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url + "/api/v1/cloudrecord/querydaily?serial=" + code + "&code=" + schemaCode + "&period=" + period);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(15000).build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (!ObjectUtils.isEmpty(entity)) {
                    return EntityUtils.toString(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            WebUtils.releaseTheBaby(httpClient, response);
        }
        return null;
    }

    /**
     * 查询设备实时直播 - 直播流列表
     * @param url LiveGBS服务器地址
     * @param serial 设备号
     * @return 直播列表
     */
    public static String streamList(String url, String serial){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url + "/api/v1/stream/list?serial=" + serial);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(15000).build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (!ObjectUtils.isEmpty(entity)) {
                    return EntityUtils.toString(entity);
                }
            }
        } catch (Exception e) {
            System.out.println("Socket Timeout Exception, I will be back。");
        } finally {
            WebUtils.releaseTheBaby(httpClient, response);
        }
        return null;
    }


/*    public static void main(String[] args) {
        byte[] snapshot = channelSnap("http://121.36.84.53:10000", "34020000001320000002");
        System.out.println("snapshot = " + snapshot);

        String channelList = channelList("http://121.36.84.53:10000", "34020000001320000002");
        System.out.println("channelList = " + channelList);

        String cloudRecord = cloudRecord("http://119.3.160.200:10000", "34020000001320000008", "20200703");
        System.out.println("cloudRecord = " + cloudRecord);
    }*/

/*    public static void main(String[] args) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String eqId = "34020000002000000014";
        try {
            client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet( "http://119.3.252.231:10000/api/v1/device/channellist?online=true&serial="+ eqId);
            //葫芦岛  安全帽级联设备
            //HttpGet httpGet = new HttpGet( "http://119.3.252.231:10000/api/v1/device/channellist?online=true&serial=34020000002000000014");
            response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String gsonStr = EntityUtils.toString(responseEntity);
                    Gson gson = new Gson();
                    EqChannelResult eqChannelResult = gson.fromJson(gsonStr, EqChannelResult.class);
                    HistoryLocus historyLocus = new HistoryLocus();
                    String workDate = DateFormatUtils.format(DateUtils.getNowDate(), "yyyy-MM-dd");
                    historyLocus.setWorkDate(workDate);
                    if (!ObjectUtils.isEmpty(eqChannelResult.getChannelList())){
                        eqChannelResult.getChannelList().stream()
                                .filter(channelListBean -> eqId.equals(channelListBean.getID()) && channelListBean.isDeviceOnline())
                                .findAny().ifPresent(channelListBean -> {
                            double lon = channelListBean.getLongitude();
                            System.out.println("lon = " + lon);
                            System.out.println("O!=lon" + (0!=lon));
                            double lat = channelListBean.getLatitude();
                            System.out.println("lat = " + lat);
                            System.out.println("O!=lat" + (0!=lat));
                        });
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            WebUtils.releaseTheBaby(client, response);
        }
    }*/
}
